<template>
  <div class="topTool">
    <el-input 
      v-model="searchName" 
      placeholder="请输入活动名称搜索" 
      clearable
      @clear="fetchActivities"
      @keyup.enter="handleSearch"
      style="width: 300px; margin-bottom: 20px;"
    >
      <template #append>
        <el-button :icon="Search" @click="handleSearch" />
      </template>
    </el-input>
  </div>

  <el-table :data="tableData" stripe style="width: 100%">
    <el-table-column prop="aid" label="活动ID" width="100" />
    <el-table-column prop="aname" label="活动名称" width="150" />
    <el-table-column prop="des" label="活动介绍" width="200" />
    <el-table-column prop="people" label="人数上限" width="100" />
    <el-table-column prop="adress" label="活动地点" width="150" />
    <el-table-column prop="reg_start" label="报名开始时间" width="180" />
    <el-table-column prop="reg_end" label="报名截止时间" width="180" />
    <el-table-column prop="act_start" label="活动开始时间" width="180" />
    <el-table-column prop="act_end" label="活动结束时间" width="180" />
    <el-table-column label="操作" width="100">
      <template #default="{ row }">
        <el-button 
          type="primary" 
          size="small" 
          @click="handleSignUp(row)"
          :disabled="!canSignUp(row)"
        >
          报名
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 报名对话框 -->
  <el-dialog v-model="signUpDialogVisible" title="活动报名" width="500px">
    <el-form :model="signUpForm" label-width="100px">
      <el-form-item label="活动名称">
        <el-input v-model="signUpForm.aname" disabled />
      </el-form-item>
      <el-form-item label="活动ID">
        <el-input v-model="signUpForm.aid" disabled />
      </el-form-item>
      <el-form-item label="学号" required>
        <el-input v-model="signUpForm.sid" placeholder="请输入学号" />
      </el-form-item>
      <el-form-item label="报名时间">
        <el-date-picker
          v-model="signUpForm.reg_data"
          type="datetime"
          placeholder="选择日期时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          disabled
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="signUpDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmSignUp">提交报名</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'
axios.defaults.withCredentials = true;
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from "element-plus";

const tableData = ref([])
const searchName = ref('')
const signUpDialogVisible = ref(false)
const signUpForm = reactive({
  aid: null,
  aname: '',
  sid: '',
  reg_data: new Date().toISOString().replace('T', ' ').substring(0, 19)
})

// 获取活动数据
const fetchActivities = async () => {
  try {
    const token = localStorage.getItem('authToken');
    const response = await axios.get("http://localhost:8080/actions", {
      headers: { Authorization: `Bearer ${token}` }
    });
    tableData.value = response.data;
  } catch (err) {
    console.error(err);
    ElMessage.error("获取活动列表失败");
  }
};

// 按名称搜索活动
const handleSearch = async () => {
  if (!searchName.value.trim()) {
    fetchActivities();
    return;
  }
  
  try {
    const token = localStorage.getItem('authToken');
    const response = await axios.get(`http://localhost:8080/actions/search?name=${searchName.value}`, {
      headers: { Authorization: `Bearer ${token}` }
    });
    tableData.value = response.data;
  } catch (err) {
    console.error(err);
    ElMessage.error("搜索活动失败");
  }
};

// 检查是否可以报名
const canSignUp = (row: any) => {
  const now = new Date();
  const regStart = new Date(row.reg_start);
  const regEnd = new Date(row.reg_end);
  return now >= regStart && now <= regEnd;
};

// 打开报名对话框
const handleSignUp = (row: any) => {
  signUpForm.aid = row.aid;
  signUpForm.aname = row.aname;
  signUpForm.sid = '';
  signUpForm.reg_data = new Date().toISOString().replace('T', ' ').substring(0, 19);
  signUpDialogVisible.value = true;
};

// 确认报名
const confirmSignUp = async () => {
  if (!signUpForm.sid) {
    ElMessage.warning("请输入学号");
    return;
  }

  try {
    const token = localStorage.getItem('authToken');
    await axios.post("http://localhost:8080/sgin", {
      aid: signUpForm.aid,
      sid: signUpForm.sid,
      reg_data: signUpForm.reg_data,
      sign_data: null, // 签到时间为空
      evaluate: null   // 评价为空
    }, {
      headers: { Authorization: `Bearer ${token}` }
    });

    ElMessage.success("报名成功");
    signUpDialogVisible.value = false;
  } catch (err) {
    console.error(err);
    ElMessage.error("报名失败");
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchActivities();
});
</script>

<style scoped>
.topTool {
  margin-bottom: 20px;
}
</style>